iT邦幫忙

0

30天 Leetcode挑戰_Day 10

  • 分享至 

  • xImage
  •  

接下來要進到medium題了!!!

本日耗時:23mins

  1. Set Mismatch
    You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
    int duplicate = -1, missing = -1;
    int n = nums.size();
    vector<int> count(n + 1, 0);

    for (int num : nums) {
        count[num]++;
    }

    for (int i = 1; i <= n; i++) {
        if (count[i] == 2) {
            duplicate = i; 
        } else if (count[i] == 0) {
            missing = i;   
        }
    }
    
    return {duplicate, missing};
}
};

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言